<template>
  <a-card :bordered="false" :loading="loading">
    <DynamicForm
      :data-source="dataColumn"
      :model-data="{ ...detailData, roleId: detailData?.role?.id }"
      @submit-form="submitForm"
      @cancel="closeTab"
    ></DynamicForm>
  </a-card>
</template>

<script setup lang="tsx">
  import { message } from 'ant-design-vue';
  import DynamicForm from '@/components/dynamicForm/index.vue';
  import useRequestDetail from '@/hooks/useRequestDetail';
  import { rusticAdminApi, createRusticAdmin, updateRusticAdmin } from '@/api/rustic/rusticAdmin';
  import { useTabsViewStore } from '@/store/modules/tabsView';
  import { ComponentsTypeEnum } from '@/enums/componentsEnum';
  import { useUserStore } from '@/store/modules/user';

  const userStore = useUserStore();
  const rustic = userStore.getRusticId();

  const route = useRoute();
  const tabsViewStore = useTabsViewStore();

  defineOptions({
    name: 'rusticAdminDetail',
  });

  const dataColumn = ref([
    {
      field: 'rusticId',
      component: ComponentsTypeEnum.Input,
      label: '乡村id',
      colProps: {
        span: 12,
      },
      rules: [],
    },
    {
      field: 'adminId',
      component: ComponentsTypeEnum.Input,
      label: '管理员id',
      colProps: {
        span: 12,
      },
      rules: [],
    },
    {
      field: 'roleId',
      component: ComponentsTypeEnum.Input,
      label: '角色id',
      colProps: {
        span: 12,
      },
      rules: [],
    },
  ]);
  const { detailData, loading } = useRequestDetail({
    apiKey: rusticAdminApi.rusticAdminDetail,
    initParams: {
      adminId: route?.query.id,
      rusticId: rustic,
    },
  });
  const submitForm = async (params) => {
    const rusticAdminId = route?.query?.id;
    const res = rusticAdminId
      ? await updateRusticAdmin({
          ...params,
          id: rusticAdminId,
        })
      : await createRusticAdmin(params);
    if (res) {
      message.success(res?.msg);
      closeTab();
    }
  };

  const closeTab = () => {
    tabsViewStore.closeCurrentTab(route);
  };
</script>

<style></style>
